﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.IO;

namespace Pcb.Common
{
    /// <summary>
    /// MD5加密,本加密后的信息不能返回原数据
    /// </summary>
    public class _MD5Encrypt
    {
        private static MD5 Md5;

        public _MD5Encrypt()
        {
            Md5 = new MD5CryptoServiceProvider();
        }

        /// <summary>
        /// 加密成Md5
        /// </summary>
        /// <param name="myString"></param>
        /// <returns></returns>
        public static string GetMD5(string myString)
        {
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] fromData = System.Text.Encoding.Unicode.GetBytes(myString);
            byte[] targetData = md5.ComputeHash(fromData);
            string byte2String = null;

            for (int i = 0; i < targetData.Length; i++)
            {
                byte2String += targetData[i].ToString("x");
            }

            return byte2String;
        } 

        /// <summary>
        /// 从字符串中获取散列值
        /// </summary>
        /// <param name="Str">要计算散列值的字符串</param>
        public static string GetMd5FromString(string Str)
        {           
            byte[] ToCompute = Encoding.Unicode.GetBytes(Str);
            byte[] Hashed = Md5.ComputeHash(ToCompute, 0, ToCompute.Length);

            return Encoding.ASCII.GetString(Hashed);
        }

        /// <summary>
        /// 从文件中获取散列值
        /// </summary>
        /// <param name="Str">要计算散列值的文件</param>
        public static string GetMd5FromFile(string FilePath)
        {
            bool IsExist = File.Exists(FilePath);

            if (IsExist) //如果文件存在
            {
                FileStream Stream = new FileStream(FilePath, FileMode.Open, FileAccess.Read);
                StreamReader Reader = new StreamReader(Stream, Encoding.Unicode);
                string Str = Reader.ReadToEnd();
                byte[] ToHash = Encoding.Unicode.GetBytes(Str);
                byte[] Hashed = Md5.ComputeHash(ToHash, 0, ToHash.Length);
                Stream.Close();

                return Encoding.ASCII.GetString(Hashed);
            }
            else
            {
                throw new FileNotFoundException("指定的文件没有找到");
            }
        }

    }
}
